//
//  LoginManager.m
//  LBBase
//
//  Created by Gary on 15/7/1.
//  Copyright (c) 2015年 Lebo. All rights reserved.
//

#import "LoginManager.h"
#import "Common.h"

@interface LoginManager () <UIAlertViewDelegate> {
    NSNumber *_isLogining;
}
@end

@implementation LoginManager

- (instancetype)init {
    self = [super init];
    if (self) {
        self.moduleID = ELoginManager;
    }
    return self;
}

#pragma mark - 业务请求处理

/**
 * @brief 请求登录
 *
 * @param [in] 用户名，密码
 * @param [out]
 * @return
 * @note
 */
- (void)loginWithData:(id)data {
    LogFunc;
    @synchronized(_isLogining) {
        if (!_isLogining || !_isLogining.boolValue) {
            NSMutableDictionary *dic = [(NSDictionary*)data objectForKey:kNetworkRequestData];
            dic[kNetReqParamVersionKey] = kAppCurrentVersion;
            dic[kNetReqParamTokenKey] = [Common currentDeivceToken];
            [BF callBusinessFunc:BusinesID(ENetworkManager, ENetReqPostLogin) inParam:data];
            _isLogining = [NSNumber numberWithBool:YES];
        }
    }
}

/**
 * @brief 登录返回后的处理
 *
 * @param [in] 网络返回数据
 * @param [out]
 * @return
 * @note
 */
- (void)loginResponse:(id)data {
    @synchronized(_isLogining) {
        [Common analyseNetworkResponseAndNotify:data
                                       moduleID:ELoginManager
                                      funIDSucc:ELoginLoginSucc
                                      funIDFail:ELoginLoginFail
                                        success:^(NSDictionary *dic) {
                                            NSDictionary *userInfo = [dic objectForKey:kNetworkResponseRetdataKey];
                                            [[NSUserDefaults standardUserDefaults] setObject:userInfo forKey:kUSKeyCurrentUserInfo];
                                            NSString *userId = ObjectStr([userInfo objectForKey:kAPIParamUserName]);
                                            [Common updateUserID:userId];
                                            NSString *token = [userInfo objectForKey:@"session"];
                                            [Common updateToken:token];
                                        }
                                        failure:^(NSDictionary *dic) {
                                            
                                        }];
        //自动登录后的重发请求
        [BF callBusinessFunc:BusinesID(ENetworkManager, ENetRetryAllRequestTasks) inParam:nil];
        _isLogining = nil;
    }
}

#pragma mark - 版本升级相关

- (void)versionUpdateRequest:(id)data{
    NSMutableDictionary *dic = [(NSDictionary*)data objectForKey:kNetworkRequestData];
    dic[kNetReqParamVersionKey] = kAppCurrentVersion;
    [BF callBusinessFunc:BusinesID(ENetworkManager, ENetReqPostVersionUpdate) inParam:data];
}

- (void)versionUpdateResponse:(id)data{
    //LogFunc;
    [Common analyseNetworkResponseAndNotify:data
                                   moduleID:ELoginManager
                                  funIDSucc:ELoginVersionUpdateSucc
                                  funIDFail:ELoginVersionUpdateFail];
}

#pragma mark - process

/**
 * @brief 登录返回后的处理
 *
 * @param [in] 网络返回数据
 * @param [out]
 * @return
 * @note
 */
- (void)saveUserInfo:(NSDictionary*)userInfo
               token:(NSString*)token
            userName:(NSString*)userName
            password:(NSString*)password {
    LogFunc;
    if (userInfo) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:userInfo];
        NSInteger count = dic.count;
        for (NSInteger i = 0; i < count; i++) {
            NSArray *allKeys = dic.allKeys;
            id key = [allKeys objectAtIndex:i];
            id object = [dic objectForKey:key];
            if (object == [NSNull null] || [object isKindOfClass:[NSNull class]]) {
                //空值重置
                [dic setObject:@"" forKey:key];
            }
        }
        [[NSUserDefaults standardUserDefaults] setObject:[NSDictionary dictionaryWithDictionary:dic]
                                                  forKey:kUSKeyCurrentUserInfo];
    }
}

#pragma mark - 框架函数

//调用业务模块功能处理
/**
 * @brief
 *
 * Detailed comments of this function
 * @param[in]
 * @param[out]
 * @return
 * @note
 */
- (int)callBusinessFunc:(NSUInteger)funcID inParam:(id)inParam outParam:(id *)outParam {
    switch (funcID) {
        case ELoginLogin: {
            if (inParam) {
                [self loginWithData:inParam];
            }
            break;
        }

        case ELoginVersionUpdate:{
            [self versionUpdateRequest:inParam];
            break;
        }
            
        default:
            break;
    }
    
    return 0;
}

/**
 * @brief
 *
 * Detailed comments of this function
 * @param[in]
 * @param[out]
 * @return
 * @note
 */
- (void)onBusinessNotify:(NSUInteger)notifyID inParam:(id)inParam {
    switch (notifyID) {
        case BusinesID(ENetworkManager, ENetReqPostLogin): {
            if (inParam) {
                [self loginResponse:inParam];
            }
            break;
        }
            
        case BusinesID(ENetworkManager, ENetReqPostVersionUpdate): {
            if (inParam) {
                [self versionUpdateResponse:inParam];
            }
            break;
        }
            
        default:
            break;
    }
}

@end

